<template>
    <a-modal :visible='visible' :title='__data.title' class='add-group-modal' @ok='submit' @cancel='cancel' :confirmLoading="__data.loading">
        <a-form :label-col='{span: 6}' :wrapper-col='{span: 16}' :model='__data.groupForm' :rules='__data.rules'>
            <a-form-item label='组编号' name='groupCode' v-bind='validateInfos.groupCode'>
                <a-input v-model:value='__data.groupForm.groupCode'/>
            </a-form-item>
            <a-form-item label='组名称' name='groupName' v-bind='validateInfos.groupName'>
                <a-input v-model:value='__data.groupForm.groupName'/>
            </a-form-item>
            <a-form-item label='绑定角色' name='roleIds' v-bind='validateInfos.roleIds'>
                <a-tree-select
                v-model:value="__data.groupForm.roleIds"
                style="width: 100%"
                :tree-data="appAndRole"
                tree-checkable
                allow-clear
                placeholder="请选择角色"/>
            </a-form-item>
            <a-form-item label='标签' name='tag'>
                <a-select
                v-model:value="__data.groupForm.tag"
                style="width: 100%"
                :options="groupTagList"
                allow-clear
                placeholder="请选择标签"/>
            </a-form-item>
            <a-form-item label='挂载默认人员' name='autoFlag' v-if="APP_AUTO_FLAG == 1">
                <a-radio-group v-model:value="__data.groupForm.autoFlag" :disabled='!!defaultData'>
                    <a-radio :value="0">否</a-radio>
                    <a-radio :value="1">是</a-radio>
                </a-radio-group> 
            </a-form-item>
            <a-form-item label='备注' name='remark'>
                <a-textarea  v-model:value='__data.groupForm.remark'/>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script lang='ts' setup>
    import { reactive, toRaw, watch, toRefs, ref, computed } from 'vue';
    import { Modal as AModal, Form as AForm, FormItem as AFormItem, 
    Input as AInput, Select as ASelect, TreeSelect as ATreeSelect, Radio as ARadio,
     RadioGroup as ARadioGroup} from 'ant-design-vue';
    import { useMessage } from '/@/hooks/web/useMessage';
    import { addGroupReq, updateGroupReq } from '/@/api/group'
    import { queryAllClientAndRole } from '/@/api/app'
    import { useUserStore } from '/@/store/modules/user'

    const { createMessage } = useMessage();

    const userStore = useUserStore();
    let APP_AUTO_FLAG = computed(() => userStore.getLoginApp?.accessableList.filter(e => e.clientId == userStore.getLoginApp?.currentId)[0].autoFlag)

    let __data = reactive({
        loading: false,
        visible: false,
        title: '新建组',
        groupForm: {
            groupId: undefined,
            groupCode: '',
            groupName: '',
            delFlag: 0,
            lockFlg: 0,
            groupType: 0,
            remark: '',
            roleIds: [],
            autoFlag: 0,
            tag: ''
        },
        rules: {
            groupCode: [{required: true, trigger: 'blur', message: '请输入组编号'}],
            groupName: [{required: true, trigger: 'blur', message: '请输入组名称'}],
            roleIds: [{required: true, trigger: 'blur', message: '请选择角色', type: 'array'}],
        }
    });
    const props = defineProps({
        visible: {
            type: Boolean,
            default: () => false
        },
        defaultData: {
            type: Object,
            default: () => undefined
        },
        groupTagList: {
            type: Array,
            default: () => undefined
        }
    })
    const emit = defineEmits(['success', 'update:visible']);
    const { resetFields, validate, validateInfos } = AForm.useForm(__data.groupForm, __data.rules);
    const { visible, groupTagList } = toRefs(props)

    const  { defaultData } = toRefs(props);
    const addInfo = async () => {
        __data.loading = true;
        const { respCode, respMsg} = await addGroupReq({...toRaw(__data.groupForm)});
        __data.loading = false;
        __data.visible = false;
        if(respCode != 200) {
            createMessage({
        message: respMsg,
        type: 'warning',
      });
            return;
        }
        createMessage({
        message: respMsg,
      });
        emit('success')
    };
    const updateInfo = async () => {
        __data.loading = true;
        const { respCode, respMsg} = await updateGroupReq({...toRaw(__data.groupForm)});
        __data.loading = false;
        __data.visible = false;
        if(respCode != 200) {
            createMessage({
        message: respMsg,
        type: 'warning',
      });
            return;
        }
        createMessage({
        message: respMsg,
      });
        emit('success')
    };
    const subAction:any = ref(null);
    subAction.value = addInfo;
    watch(visible, (nv: boolean) => {
        if(!nv) 
            resetFields();
        else {
            __data.title = props.defaultData ? '编辑组' : '新建组';
            subAction.value = props.defaultData ? updateInfo : addInfo;
            __data.groupForm.groupId = props.defaultData?.groupId;
            __data.groupForm.groupCode = props.defaultData?.groupCode;
            __data.groupForm.groupName = props.defaultData?.groupName;
            __data.groupForm.roleIds = props.defaultData?.userGroupRoleRelationModelList.map(e => e.roleId) || [];
            __data.groupForm.remark = props.defaultData?.remark;
            __data.groupForm.tag = props.defaultData?.tag;
            __data.groupForm.autoFlag = props.defaultData?.autoFlag || 0;
        }
    })

    function submit() {
        validate()
        .then(() => {
            subAction.value();
            emit('update:visible', false)
        })
        .catch(err => console.log('error', err))
    }
    function cancel() {
        emit('update:visible', false)
    }

    let appAndRole = ref([]);
    function formatTreeData(s) {
        function formatLevel1(s) {
            return s.map(e =>({
                title: e.clientName,
                value: `app_${e.id}`,
                children: formatLevel2more(e.roleModelList),
                checkable: false,
            }))
        }
        function formatLevel2more(s) {
            if(!s || !s.length) return undefined;
            return s.map(e => ({
                title: e.roleName,
                value: e.roleId,
            }))
        }
        if(!s || !s.length) return undefined;
        return formatLevel1(s);
    }
    const query = async function() {
        const {data} = await queryAllClientAndRole()
        appAndRole.value = formatTreeData(data) || [];
    };
    query()


    defineExpose({
        visible
    })

</script>

<style lang='less'>
.add-group-modal {
    .ant-modal-body {
        padding: 20px;
    }
}
</style>